package com.example.it.studypulltoreference;

import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;

import java.util.ArrayList;
import java.util.List;

public class HomeActivity extends AppCompatActivity implements PullToRefreshListView.OnLoad {

    private int stepCount = 30;//每次刷新加载的内容的数量
    private List<String> stringList = new ArrayList<String>();
    private DataAdapter adapter;
    private PullToRefreshListView listView;

    /*
    * 初始化一些模拟的数据
    * */
    private void initData() {
        for (int i = 0; i < 200; i++) {
            stringList.add("程序猿" + (i + 1));
        }
    }

    private void init() {
        adapter = new DataAdapter(this, new ArrayList<String>());
        this.listView.setAdapter(adapter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        listView = (PullToRefreshListView) this.findViewById(R.id.lvData);

        init();

        initData();

        //设置刷新数据的方法
        listView.setOnLoad(this);

        loadData(0, null);
    }

    /*
    * 想Adapter中的数据源填充数据
    * */
    @Override
    public void loadData(final int beginIndex, final ProgressBar pb) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //如果pb不为null不是初始化数据
                if (pb != null) {
                    //模拟加载中 睡眠 2秒
                    SystemClock.sleep(2000l);
                }

                for (int i = beginIndex; i < beginIndex + stepCount; i++) {
                    if (i < stringList.size())
                        adapter.addItem(stringList.get(i));
                }
                //加载数据完成回更新UI
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (pb != null)
                            pb.setVisibility(View.GONE);
                        //刷新Adapter
                        adapter.notifyDataSetChanged();
                    }
                });

            }
        }).start();
    }
}
